/*
 * @Author: sy
 * @Date: 2021-08-15 21:42:43
 * @LastEditTime: 2022-08-31 16:29:15
 * @Description: file content
 */
import store from '@/store'
import axios from 'axios'
import * as Vue from 'vue'
import account from '@/store/modules/admin/modules/account';
import { Message } from 'element-ui';

const timeout = 5 * 60 * 1000; // 请求延迟
const errorDuration = 3 * 1000; // 错误显示延迟

// 创建一个 axios 实例
const service = axios.create({
  timeout, // 请求超时时间
  // headers: {
  //     "Access-Control-Allow-Origin": "*",
  //     "Content-Type": "application/json;charset=utf-8"
  // }
});

// 请求拦截器
service.interceptors.request.use(
  config => config,
  error => {
    // 发送失败
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  result => {
    const res = result.data;
    console.log("service.interceptors.response res==", res, res.resultdata);
    if (typeof res.resultdata === "string" && res.resultdata) {
      res.resultdata = JSON.parse(res.resultdata);
    }
    const msgcode = String(res.msgcode);
    // 异常处理
    if (msgcode != "1") {
      // code 为 -3表示token 失效
      if (msgcode == "-3") {
        // store.dispatch("d2admin/account/logout");
        account().logout()
      }
      // 根据错误码首位来判断使用哪种方式提示用户，约定的错误为7位；不为7位的默认当做系统错误处理；
      if (msgcode?.length == 7) {
        const firstCode = msgcode.substring(0, 1);
        if (firstCode != 2) {
          // 1、警告提醒用户；2、需要用户做操作的提示，如弹框确认；3、普通告知提示；4、错误提示；
          if (firstCode == 1) {
            Message({
              message: res.message || "error",
              type: 'warning',
              duration: errorDuration
            });
          } else if (firstCode == 3) {
            Message({
              message: res.message || "error",
              type: 'warning',
              duration: errorDuration
            });
          } else {
            // firstCode == 4 系统错误   firstCode不为1、2、3的其他情况默认当做系统错误提示；
            if (
              res.debuginfo &&
              res.debuginfo.debugdata &&
              Array.isArray(res.debuginfo.debugdata)
            ) {
              // 有traceid 将traceId拼接到提示信息中，并换行显示
              let traceIds = [];
              res.debuginfo.debugdata.map(item => {
                traceIds.push(item.traceId);
              });
              const traceIdInfo = traceIds.join(",");
              if (traceIdInfo) {
                const clickHander = () => {
                  document
                    .getElementById("ddmg_message_tips_err_id")
                    .setAttribute("style", "color:#E22319;display:block");
                };
                const vue = new Vue();
                const h = vue.$createElement;
                Message({
                  type: "error",
                  message: h("p", { style: "background-color:#fef0f0" }, [
                    h(
                      "p",
                      {
                        style: "color:#E22319;display:inline",
                        on: { click: clickHander },
                        attrs: { id: "ddmg_message_tips_err_detail_click" }
                      },
                      res.message
                    ),
                    h(
                      "p",
                      {
                        style: "color:#E22319;display:none",
                        attrs: { id: "ddmg_message_tips_err_id" }
                      },
                      "请求ID: " + traceIdInfo
                    )
                  ]),
                  duration: errorDuration
                });
              } else {
                Message({
                  type: "error",
                  message: res.message || "error",
                  duration: errorDuration
                });
              }
            } else if(msgcode == "4150600"){
              console.log("继续往下执行")
            } else {
              Message({
                type: "error",
                message: res.message || "error",
                duration: errorDuration
              });
            }
          }
        }
      }else {
        Message({
          type: "error",
          message: res.message || "error",
          duration: errorDuration
        });
      }
    }
    return Promise.resolve(res);
  },
  error => {
    Message({
      type: "error",
      message: error.message || "error",
      duration: errorDuration
    });
    return Promise.reject(error);
  }
);

export default service;
